import axios from 'axios'
// import { MessageBox, Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor请求拦截
service.interceptors.request.use(
  config => {
    const token = store.state.user.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor响应拦截
service.interceptors.response.use(
  response => {
    // 如果登录返回信息success为true，则直接返回
    if (response.data.success) {
      return response
    } else {
      // 否则返回错误数据，response.data.message传参给 发送ajax时，try...catch里面的catch的error
      return Promise.reject(response.data.message)
    }
  },
  // 返回4开通，都会走error
  error => {
    // 如果路由过期，后台则会返回10002
    if (error.response.data.code === 10002) {
      store.dispatch('user/logout')
      router.push('login?return_url=' + router.currentRoute.path)
    }
    return Promise.reject(error)
  }
)

export default service
